<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;

use App\Cases;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CaseController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex()
    {
        $pageSize = 10;
        $cases = Cases::where('isDeleted',0)->paginate($pageSize);

        $data = array(
            'cases' => $cases
        );
        return view("admin.cases.listcase",$data);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getCreate(Request $request)
    {
        $data = array();
        $id = $request->get('id');
        if ($id){
            $case = Cases::where('id',$id)->first();
            if ($case) {
                $data['case'] = $case;
            }
        }

        return view("admin.cases.addcase",$data);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postSave(Request $request)
    {
        $id = $request->id;

        $now = time();
        if ($id) { // 更新
            $case = Cases::where('id',$id)->first();
        } else { // 插入
            $case = new Cases();
            $case->created = $now;
        }

        $case->name = $request->get("name");
        $case->mainTitle = $request->get("mainTitle");
        $case->subTitle = $request->get("subTitle");
        $case->content  = $request->get("content");
        $case->updated = $now;
        if ($case->save()){
            return redirect("admin/cases/index");
        } else {
            return redirect()->back()->withInput()->withErrors('保存失败！');
        }
    }

    public function postDelete(Request $request) {
        $data = array();
        $id = $request->get('id');
        if (!$id) {
            $data['code'] = 1002;
            $data['msg']  = '操作失败';
            echo json_encode($data);
            exit;
        }

        $update = array(
            'isDeleted' => 1
        );
        $res = Cases::where('id',$id)->where('isDeleted',0)->update($update);

        if ($res) {
            $data['code'] = 1001;
            $data['msg']  = '操作成功';
            echo json_encode($data);
            exit;
        } else {
            $data['code'] = 1002;
            $data['msg']  = '操作失败';
            echo json_encode($data);
            exit;
        }
    }
}
